package cn.edu.nchu.comic_strip.ui.bookpage;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.icu.util.Calendar;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Window;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import java.util.List;
import java.util.Locale;

import cn.edu.nchu.comic_strip.App;
import cn.edu.nchu.comic_strip.R;
import cn.edu.nchu.comic_strip.database.dao.PageDao;
import cn.edu.nchu.comic_strip.entity.Page;


public class BookPageActivity extends AppCompatActivity implements BookPageFragment.ComicFragmentButtonClickListener {

    private ViewPager viewPager;
    private BookPageAdapter adapter;
    private int bookId;
    private int stopPage;
    private static final int AUTO_SCROLL_DELAY = 24; // 延迟时间，单位为毫秒

    private PageDao pageDao = App.getAppDatabase().getPageDao();
    private Handler autoScrollHandler;
    private Runnable autoScrollRunnable;
    private String[] textSizeButtonText = {"小", "中", "大"};
    private int textSizeIndex = 1; // 默认字体大小的索引值为1
    private boolean isProtect = false;//护眼模式是否开启

    private BroadcastReceiver batteryReceiver;
    private BatteryView horizontalBatteryView;
    private TextView timeDisplayTextView;
    private ConstraintLayout constraintLayout;


    private Handler timeHandler = new Handler();
    private Runnable updateTimeRunnable;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /* 隐藏标题栏 */
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        /* 隐藏状态栏 */
        supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
        getWindow().setAttributes(lp);

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_book_page);
        // 隐藏标题栏
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        horizontalBatteryView = (BatteryView) findViewById(R.id.horizontalBattery);
        timeDisplayTextView = findViewById(R.id.time_display);
        constraintLayout = findViewById(R.id.activity_book_page_constraintLayout);
        batteryReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                int batteryLevel = (int) ((level / (float) scale) * 100);

                horizontalBatteryView.setPower(batteryLevel);
            }
        };
        // 注册广播接收器以监听电池状态变化
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryReceiver, filter);

        updateTimeRunnable = new Runnable() {
            @Override
            public void run() {
                // Get the current time
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault()); // 使用 "HH:mm" 表示24小时制
                String currentTime = dateFormat.format(calendar.getTime());

                // Update the time display TextView
                timeDisplayTextView.setText(currentTime);

                // Schedule the next update after a delay
                timeHandler.postDelayed(this, 1000); // Update every second
            }
        };


        timeHandler.post(updateTimeRunnable);

        // 接收bookId
        Intent intent = getIntent();
        // 接收bookid 默认为0
        bookId = intent.getIntExtra("bookId", 0);
        // 接收传递的指定页标参数 默认-1
        stopPage = intent.getIntExtra("stopPage", -1);

        adapter = new BookPageAdapter(getSupportFragmentManager(), getPages(), textSizeIndex, this,isProtect);

        viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(adapter);

        // 将字体修改以及点击切换下一页的接口 回调给每个fragment
        for (int i = 0; i < adapter.getCount(); i++) {
            Fragment fragment = adapter.getItem(i);
            if (fragment instanceof BookPageFragment) {
                ((BookPageFragment) fragment).setButtonClickListener(this);
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(batteryReceiver);
        timeHandler.removeCallbacks(updateTimeRunnable);
    }

    /**
     * 根据传递的bookid 获取该书的页面数据
     *
     * @return
     */
    private List<Page> getPages() {
        List<Page> comicData;
        comicData = pageDao.getPagesByBookId(bookId);
        return comicData;
    }

    /**
     * 当从其他的activity切换到该活动 自动滚动到指定页标
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (stopPage != -1) {
            startAutoScroll(stopPage);
        }
    }

    /**
     * 活动暂停时 停止滚动
     */
    @Override
    protected void onPause() {
        super.onPause();
        stopAutoScroll();
    }


    /**
     * 自动轮播 到指定页标
     *
     * @param stop
     */
    private void startAutoScroll(int stop) {
        autoScrollHandler = new Handler(Looper.getMainLooper());
        autoScrollRunnable = new Runnable() {
            @Override
            public void run() {
                int currentItem = viewPager.getCurrentItem();
                int nextItem = currentItem + 1;
                if (nextItem >= adapter.getCount()) {
                    SharedPreferences settings = getSharedPreferences("MyPrefsFile", 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putBoolean("AutoPlay", false);
                    editor.apply();
                }

                if (stop != -1) {   // 没有书签，不轮播
                    viewPager.setCurrentItem(nextItem, true);
                }

                if (currentItem == stop) {   // 如果到达书签页
                    stopAutoScroll();   // 停止轮播
                } else {
                    autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY);
                }
            }
        };
        autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY);
    }

    /**
     * 停止滚动
     */
    public void stopAutoScroll() {  // 停止轮播
        if (autoScrollHandler != null && autoScrollRunnable != null) {
            autoScrollHandler.removeCallbacks(autoScrollRunnable);
        }
    }


    private void changeTextSize() {
        textSizeIndex++;

        if (textSizeIndex == textSizeButtonText.length) {
            textSizeIndex = 0;
        }
        adapter.setTextSizeIndex(textSizeIndex); // 将改变的大小索引传给适配器

        // 遍历所有 Fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment instanceof BookPageFragment) {
                // 获取对应 Fragment 的文本视图引用
                BookPageFragment myFragment = (BookPageFragment) fragment;
                // 更改字体大小
                updateTextSize(myFragment);
            }
        }
    }

    private void updateTextSize(BookPageFragment fragment) {
        TextView titleView = fragment.getTitleView(); // 获取标题组件
        TextView summaryView = fragment.getSummaryView(); // 获取内容组件
        TextView pageView = fragment.getPageView(); // 获取页数组件
        Button textSizeButton = fragment.getTextSizeButton();
        // 更改字体大小
        titleView.setTextSize(fragment.getTitleTextSize()[textSizeIndex]); // 改变标题大小
        summaryView.setTextSize(fragment.getSummaryTextSize()[textSizeIndex]); // 改变内容大小
        pageView.setTextSize(fragment.getPageTextSize()[textSizeIndex]); // 改变页数大小
        textSizeButton.setText(fragment.getTextSizeButtonText()[textSizeIndex]); // 改变字体大小按钮的字体
    }

    @Override
    public void onTextSizeButtonClick() {
        changeTextSize();
    }

    @Override
    public void onNextPageClicked() {
        startAutoScroll(viewPager.getCurrentItem());
    }

    @Override
    public void onSelectPageClicked(int pagesIndex) {
        jumpToPage(pagesIndex);
    }

    @Override
    public void protectEye(boolean isStart) {
        changeBackground(isStart);
    }

    private void changeBackground(boolean isStart) {
        isProtect = isStart;
        adapter.setProtect(isProtect); // 将改变的大小索引传给适配器

        int newBackgroundColor = isStart ? Color.parseColor("#CCFFCC") : Color.WHITE;

        // 遍历所有 Fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment instanceof BookPageFragment) {
                // 获取对应 Fragment 的根视图引用
                BookPageFragment myFragment = (BookPageFragment) fragment;
                View rootView = myFragment.getView();
                ImageButton protectEyeButton = ((BookPageFragment) fragment).getProtectEyeButton();
                if(protectEyeButton != null && isStart){
                    protectEyeButton.setTag("开启");
                    protectEyeButton.setBackground(this.getResources().getDrawable(R.drawable.ic_protect_eye));
                }
                else if(protectEyeButton != null){
                    protectEyeButton.setTag("关闭");
                    protectEyeButton.setBackground(this.getResources().getDrawable(R.drawable.ic_no_protect_eye));
                }
                constraintLayout.setBackgroundColor(newBackgroundColor);
            }
        }
    }

    /**
     * 跳转到指定页数
     *
     * @param pageNumber 要跳转的页面索引
     */
    private void jumpToPage(int pageNumber) {
        // 判断pageNumber是否有效
        if (pageNumber >= 0 && pageNumber < adapter.getCount()) {
            viewPager.setCurrentItem(pageNumber, true); // 跳转到指定页面
        } else {
            // 页面索引无效，进行相应的处理，例如提示用户或执行其他操作
            // 这里只是简单地打印错误信息
            System.out.println("Invalid page number");
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        if (hasFocus) {
//            View decorView = getWindow().getDecorView();
//            WindowInsetsController controller = decorView.getWindowInsetsController();
//            if (controller != null) {
//                controller.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
//                controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
//            }
//        }
//    }
}
